package com.kizuki.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 *
 * https://leetcode-cn.com/problems/spiral-matrix/
 */
public class 螺旋矩阵 {

    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            ArrayList<Integer> res = new ArrayList<>();
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return res;
            }
            int up = 0;
            int down = matrix.length - 1;
            int left = 0;
            int right = matrix[0].length - 1;
            while(true) {
                for (int i = left; i <= right; i++) {
                    res.add(matrix[up][i]);
                }
                if (++up > down) {
                    return res;
                }
                for (int i = up; i <= down; i++) {
                    res.add(matrix[i][right]);
                }
                if (--right < left) {
                    return res;
                }
                for (int i = right; i >= left; i--) {
                    res.add(matrix[down][i]);
                }
                if (--down < up) {
                    return res;
                }
                for (int i = down; i >= up; i--) {
                    res.add(matrix[i][left]);
                }
                if (++left > right) {
                    return res;
                }
            }
        }
    }
}
